package com.along.utility.common.utils;

import org.springframework.cglib.beans.BeanCopier;

import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author pingguanfei
 * @date 2021-01-12 13:28:42
 *
 */
public class BeanUtils {

	private static final ConcurrentHashMap<String, BeanCopier> mapCaches = new ConcurrentHashMap<>();

	private BeanUtils() {
	}

	/**
	 *
	 * @param sources
	 * @param target
	 * @author pingguanfei
	 * @date 2021-01-15 15:17:35
	 *
	 */
	public static <E, T> T copy(E sources, T target) {
		if (sources != null) {
			String baseKey = generateKey(sources.getClass(), target.getClass());
			BeanCopier copier;
			if (!mapCaches.containsKey(baseKey)) {
				copier = BeanCopier.create(sources.getClass(), target.getClass(), false);
				mapCaches.put(baseKey, copier);
			} else {
				copier = mapCaches.get(baseKey);
			}
			copier.copy(sources, target, null);
			return target;
		}
		return null;
	}

	/**
	 *
	 * @param src
	 * @param tag
	 * @return
	 * @author pingguanfei
	 * @date 2021-04-20 11:27:30
	 *
	 */
	private static String generateKey(Class<?> src, Class<?> tag) {
		return String.format("%s%s", src.toString(), tag.toString());
	}
}
